package com.stenio.fancat.service.shop;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.domain.shop.FcCategory;
import com.stenio.fancat.domain.shop.FcShop;
import com.stenio.fancat.form.shop.CateogryForm;
import com.stenio.fancat.mapper.shop.FcCategoryMapper;
import com.stenio.fancat.mapper.shop.FcShopMapper;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;


@Service
public class CategoryService extends ServiceImpl<FcCategoryMapper, FcCategory> {

	@Autowired
	private FcCategoryMapper fcCategoryMapper;

	@Autowired
	private FcShopMapper fcShopMapper;

	private static final Logger logger = LoggerFactory.getLogger(CategoryService.class);

	/**
     * 保存品类
	 * @param form
     * @return
     */
	@CacheEvict(value = {"category"},allEntries = true)
	public FcCategory saveCategory(CateogryForm form){
		FcCategory fcCategory = fcCategoryMapper.selectLastOne();
		FcCategory category = new FcCategory();
		BeanUtils.copyProperties(form,category);
		Date date = new Date();
		category.setCreateTime(date);
		category.setUpdateTime(date);
		category.setSortOrder(fcCategory.getSortOrder()+1);
		fcCategoryMapper.insert(category);
		return category;
	}

    /**
     * 更新品类
	 * @param form
	 */
	public FcCategory updateCategory(CateogryForm form){
		FcCategory category = new FcCategory();
		BeanUtils.copyProperties(form,category);
		fcCategoryMapper.updateAll(category);
		return category;
	}

	/**
	 * 按主键查询
	 * @param id
	 * @return
	 */
	public FcCategory findById(Integer id){
		return fcCategoryMapper.findById(id);
	}

	/**
	 * 删除品类
	 * @param id
	 * @throws Exception
	 */
	@CacheEvict(value = {"category"},allEntries = true)
	public int deleteById(Integer id){
		List<FcShop> fcShops = fcShopMapper.selectByCategoryId(id);
		if(CollectionUtils.isEmpty(fcShops)) {
			return fcCategoryMapper.deleteById(id);
		}
		return 0;
	}

	/**
	 * 根据父类目查询
	 * @param parentId
	 * @return
	 */
	public List<FcCategory> findByParentId(Integer parentId){
		return fcCategoryMapper.findByParentId(parentId);
	}

	/**
	 * 查询所有二级分类
	 * @return
	 */
	@Cacheable(cacheNames = {"category"},key = "1",unless = "#result == null")
	public List<FcCategory> findSecondaryAll() {
		List<FcCategory> secondaryAll = fcCategoryMapper.findSecondaryAll();
		List<FcCategory> newList = new ArrayList<>();
		for (FcCategory fcCategory : secondaryAll) {
			List<FcShop> fcShops = fcShopMapper.selectByCategoryId(fcCategory.getId());
			if (CollectionUtils.isNotEmpty(fcShops)) {
				newList.add(fcCategory);
			}
		}
		return newList;
	}

}
